from django.db import models
from jrcmodel.models import MyConstants, CST
import math

class JrcSignal(models.Model):
    status_id = models.IntegerField(choices = MyConstants.STATUS_CHOICES)
    cst_id = models.ForeignKey(CST)
    entry_value = models.DecimalField(max_digits = 10, decimal_places = 5)
    exit_value = models.DecimalField(max_digits = 10, decimal_places = 5)

    direction_first = models.CharField(max_length = 2, choices = MyConstants.DIRECTION_CHOICES)
#    exit_value_first = models.DecimalField(max_digits = 10, decimal_places = 5)
    date_first = models.DateField()

    direction_second = models.CharField(max_length = 2, choices = MyConstants.DIRECTION_CHOICES)
#    entry_value_second = models.DecimalField(max_digits = 10, decimal_places = 5)
    date_second = models.DateField()

    # Cache Market
    _market = None

    def __unicode__(self):
        return "%s->%s (%s->%s), (%s->%s)" % (self.date_first, self.date_second, self.direction_first, self.direction_second, self.entry_value, self.exit_value)

    def get_direction_first_name(self):
        v = self.direction_first
        if self.direction_first == "B":
            v = "Buy"
        if self.direction_first == "S":
            v = "Sell"
        return v

    def get_direction_second_name(self):
        v = self.direction_second
        if self.direction_second == "B":
            v = "Buy"
        if self.direction_second == "S":
            v = "Sell"
        return v

    def get_market(self):
        if self._market == None:
#            print "Searching for CST #%d" % self.cst_id
#            cst = CST.objects.get(pk = self.cst_id)
#            print "Got CST: %s" % cst.name
            self._market = self.cst_id.market_direction_1.market_id
        return self._market
    
    def get_pips(self):
        m = self.get_market()
#        print "Price decimal places: %d" % m.price_decimal_places
        profit = 0
        if self.direction_first == "B":
            profit = self.exit_value - self.entry_value
        else:
            profit = self.entry_value - self.exit_value
            
#        print "Profit: %f" % profit
        p = int(math.pow(10, m.price_decimal_places))
#        print "Power of 10 is: %d" % p
        return profit * p
